package memory

import (
	"context"
	"errors"
	"fmt"
	"sort"
	"strconv"
	"sync"
	"time"

	"github.com/louloulin/dataflare/pkg/state/store"
)

// MemoryStateStore 表示内存状态存储
type MemoryStateStore struct {
	// states 是状态映射表
	states map[string]store.State
	// config 是配置
	config map[string]interface{}
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryKVState 表示内存键值状态
type MemoryKVState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string][]byte
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryTableState 表示内存表格状态
type MemoryTableState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string]map[string][]byte
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryDocumentState 表示内存文档状态
type MemoryDocumentState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string][]byte
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryCounterState 表示内存计数器状态
type MemoryCounterState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string]int64
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryGaugeState 表示内存度量值状态
type MemoryGaugeState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string]float64
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// HistogramData 表示直方图数据
type HistogramData struct {
	// Values 是值列表
	Values []float64
	// Count 是计数
	Count int64
	// Sum 是总和
	Sum float64
	// Min 是最小值
	Min float64
	// Max 是最大值
	Max float64
}

// MemoryHistogramState 表示内存直方图状态
type MemoryHistogramState struct {
	// name 是状态名称
	name string
	// data 是数据映射表
	data map[string]*HistogramData
	// ttl 是生存时间
	ttl time.Duration
	// persistent 是持久化标志
	persistent bool
	// mu 是互斥锁
	mu sync.RWMutex
}

// MemoryStateStoreFactory 表示内存状态存储工厂
type MemoryStateStoreFactory struct{}

// NewMemoryStateStore 创建一个新的内存状态存储
func NewMemoryStateStore() *MemoryStateStore {
	return &MemoryStateStore{
		states: make(map[string]store.State),
		config: make(map[string]interface{}),
	}
}

// Init 初始化状态存储
func (s *MemoryStateStore) Init(ctx context.Context, config map[string]interface{}) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.config = config
	return nil
}

// Close 关闭状态存储
func (s *MemoryStateStore) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, state := range s.states {
		err := state.Close(ctx)
		if err != nil {
			return err
		}
	}
	s.states = make(map[string]store.State)
	return nil
}

// CreateState 创建状态
func (s *MemoryStateStore) CreateState(ctx context.Context, config *store.StateConfig) (store.State, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	// 检查状态是否已存在
	if _, ok := s.states[config.Name]; ok {
		return nil, fmt.Errorf("state %s already exists", config.Name)
	}

	// 创建状态
	var state store.State
	var err error
	switch config.Type {
	case store.StateTypeKV:
		state = NewMemoryKVState(config.Name, config.TTL, config.Persistent)
	case store.StateTypeTable:
		state = NewMemoryTableState(config.Name, config.TTL, config.Persistent)
	case store.StateTypeDocument:
		state = NewMemoryDocumentState(config.Name, config.TTL, config.Persistent)
	case store.StateTypeCounter:
		state = NewMemoryCounterState(config.Name, config.TTL, config.Persistent)
	case store.StateTypeGauge:
		state = NewMemoryGaugeState(config.Name, config.TTL, config.Persistent)
	case store.StateTypeHistogram:
		state = NewMemoryHistogramState(config.Name, config.TTL, config.Persistent)
	default:
		return nil, fmt.Errorf("unsupported state type: %s", config.Type)
	}

	// 存储状态
	s.states[config.Name] = state

	return state, err
}

// GetState 获取状态
func (s *MemoryStateStore) GetState(ctx context.Context, name string) (store.State, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	state, ok := s.states[name]
	if !ok {
		return nil, fmt.Errorf("state %s not found", name)
	}
	return state, nil
}

// DeleteState 删除状态
func (s *MemoryStateStore) DeleteState(ctx context.Context, name string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	state, ok := s.states[name]
	if !ok {
		return fmt.Errorf("state %s not found", name)
	}
	err := state.Close(ctx)
	if err != nil {
		return err
	}
	delete(s.states, name)
	return nil
}

// ListStates 列出所有状态
func (s *MemoryStateStore) ListStates(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	states := make([]string, 0, len(s.states))
	for name := range s.states {
		states = append(states, name)
	}
	return states, nil
}

// Flush 刷新状态
func (s *MemoryStateStore) Flush(ctx context.Context) error {
	// 内存状态存储不需要刷新
	return nil
}

// NewMemoryKVState 创建一个新的内存键值状态
func NewMemoryKVState(name string, ttl time.Duration, persistent bool) *MemoryKVState {
	return &MemoryKVState{
		name:       name,
		data:       make(map[string][]byte),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryKVState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryKVState) Type() store.StateType {
	return store.StateTypeKV
}

// Scope 返回状态作用域
func (s *MemoryKVState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryKVState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string][]byte)
	return nil
}

// Get 获取值
func (s *MemoryKVState) Get(ctx context.Context, key string) ([]byte, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	value, ok := s.data[key]
	if !ok {
		return nil, fmt.Errorf("key %s not found", key)
	}
	return value, nil
}

// Set 设置值
func (s *MemoryKVState) Set(ctx context.Context, key string, value []byte) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = value
	return nil
}

// Delete 删除值
func (s *MemoryKVState) Delete(ctx context.Context, key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.data, key)
	return nil
}

// Keys 获取所有键
func (s *MemoryKVState) Keys(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	keys := make([]string, 0, len(s.data))
	for key := range s.data {
		keys = append(keys, key)
	}
	return keys, nil
}

// NewMemoryTableState 创建一个新的内存表格状态
func NewMemoryTableState(name string, ttl time.Duration, persistent bool) *MemoryTableState {
	return &MemoryTableState{
		name:       name,
		data:       make(map[string]map[string][]byte),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryTableState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryTableState) Type() store.StateType {
	return store.StateTypeTable
}

// Scope 返回状态作用域
func (s *MemoryTableState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryTableState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string]map[string][]byte)
	return nil
}

// GetRow 获取行
func (s *MemoryTableState) GetRow(ctx context.Context, key string) (map[string][]byte, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	row, ok := s.data[key]
	if !ok {
		return nil, fmt.Errorf("key %s not found", key)
	}
	return row, nil
}

// GetCell 获取单元格
func (s *MemoryTableState) GetCell(ctx context.Context, key string, column string) ([]byte, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	row, ok := s.data[key]
	if !ok {
		return nil, fmt.Errorf("key %s not found", key)
	}
	value, ok := row[column]
	if !ok {
		return nil, fmt.Errorf("column %s not found", column)
	}
	return value, nil
}

// SetRow 设置行
func (s *MemoryTableState) SetRow(ctx context.Context, key string, row map[string][]byte) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = row
	return nil
}

// SetCell 设置单元格
func (s *MemoryTableState) SetCell(ctx context.Context, key string, column string, value []byte) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	row, ok := s.data[key]
	if !ok {
		row = make(map[string][]byte)
		s.data[key] = row
	}
	row[column] = value
	return nil
}

// DeleteRow 删除行
func (s *MemoryTableState) DeleteRow(ctx context.Context, key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.data, key)
	return nil
}

// DeleteCell 删除单元格
func (s *MemoryTableState) DeleteCell(ctx context.Context, key string, column string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	row, ok := s.data[key]
	if !ok {
		return nil
	}
	delete(row, column)
	return nil
}

// Keys 获取所有键
func (s *MemoryTableState) Keys(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	keys := make([]string, 0, len(s.data))
	for key := range s.data {
		keys = append(keys, key)
	}
	return keys, nil
}

// Columns 获取所有列
func (s *MemoryTableState) Columns(ctx context.Context, key string) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	row, ok := s.data[key]
	if !ok {
		return nil, fmt.Errorf("key %s not found", key)
	}
	columns := make([]string, 0, len(row))
	for column := range row {
		columns = append(columns, column)
	}
	return columns, nil
}

// NewMemoryDocumentState 创建一个新的内存文档状态
func NewMemoryDocumentState(name string, ttl time.Duration, persistent bool) *MemoryDocumentState {
	return &MemoryDocumentState{
		name:       name,
		data:       make(map[string][]byte),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryDocumentState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryDocumentState) Type() store.StateType {
	return store.StateTypeDocument
}

// Scope 返回状态作用域
func (s *MemoryDocumentState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryDocumentState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string][]byte)
	return nil
}

// Get 获取文档
func (s *MemoryDocumentState) Get(ctx context.Context, id string) ([]byte, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	document, ok := s.data[id]
	if !ok {
		return nil, fmt.Errorf("document %s not found", id)
	}
	return document, nil
}

// Set 设置文档
func (s *MemoryDocumentState) Set(ctx context.Context, id string, document []byte) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[id] = document
	return nil
}

// Delete 删除文档
func (s *MemoryDocumentState) Delete(ctx context.Context, id string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.data, id)
	return nil
}

// Query 查询文档
func (s *MemoryDocumentState) Query(ctx context.Context, query string) ([][]byte, error) {
	// 简单实现，返回所有文档
	s.mu.RLock()
	defer s.mu.RUnlock()
	documents := make([][]byte, 0, len(s.data))
	for _, document := range s.data {
		documents = append(documents, document)
	}
	return documents, nil
}

// IDs 获取所有ID
func (s *MemoryDocumentState) IDs(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	ids := make([]string, 0, len(s.data))
	for id := range s.data {
		ids = append(ids, id)
	}
	return ids, nil
}

// NewMemoryCounterState 创建一个新的内存计数器状态
func NewMemoryCounterState(name string, ttl time.Duration, persistent bool) *MemoryCounterState {
	return &MemoryCounterState{
		name:       name,
		data:       make(map[string]int64),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryCounterState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryCounterState) Type() store.StateType {
	return store.StateTypeCounter
}

// Scope 返回状态作用域
func (s *MemoryCounterState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryCounterState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string]int64)
	return nil
}

// Get 获取计数
func (s *MemoryCounterState) Get(ctx context.Context, key string) (int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	value, ok := s.data[key]
	if !ok {
		return 0, nil
	}
	return value, nil
}

// Increment 增加计数
func (s *MemoryCounterState) Increment(ctx context.Context, key string, amount int64) (int64, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	value, ok := s.data[key]
	if !ok {
		value = 0
	}
	value += amount
	s.data[key] = value
	return value, nil
}

// Decrement 减少计数
func (s *MemoryCounterState) Decrement(ctx context.Context, key string, amount int64) (int64, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	value, ok := s.data[key]
	if !ok {
		value = 0
	}
	value -= amount
	s.data[key] = value
	return value, nil
}

// Reset 重置计数
func (s *MemoryCounterState) Reset(ctx context.Context, key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = 0
	return nil
}

// Keys 获取所有键
func (s *MemoryCounterState) Keys(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	keys := make([]string, 0, len(s.data))
	for key := range s.data {
		keys = append(keys, key)
	}
	return keys, nil
}

// NewMemoryGaugeState 创建一个新的内存度量值状态
func NewMemoryGaugeState(name string, ttl time.Duration, persistent bool) *MemoryGaugeState {
	return &MemoryGaugeState{
		name:       name,
		data:       make(map[string]float64),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryGaugeState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryGaugeState) Type() store.StateType {
	return store.StateTypeGauge
}

// Scope 返回状态作用域
func (s *MemoryGaugeState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryGaugeState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string]float64)
	return nil
}

// Get 获取度量值
func (s *MemoryGaugeState) Get(ctx context.Context, key string) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	value, ok := s.data[key]
	if !ok {
		return 0, nil
	}
	return value, nil
}

// Set 设置度量值
func (s *MemoryGaugeState) Set(ctx context.Context, key string, value float64) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = value
	return nil
}

// Adjust 调整度量值
func (s *MemoryGaugeState) Adjust(ctx context.Context, key string, delta float64) (float64, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	value, ok := s.data[key]
	if !ok {
		value = 0
	}
	value += delta
	s.data[key] = value
	return value, nil
}

// Reset 重置度量值
func (s *MemoryGaugeState) Reset(ctx context.Context, key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data[key] = 0
	return nil
}

// Keys 获取所有键
func (s *MemoryGaugeState) Keys(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	keys := make([]string, 0, len(s.data))
	for key := range s.data {
		keys = append(keys, key)
	}
	return keys, nil
}

// NewMemoryHistogramState 创建一个新的内存直方图状态
func NewMemoryHistogramState(name string, ttl time.Duration, persistent bool) *MemoryHistogramState {
	return &MemoryHistogramState{
		name:       name,
		data:       make(map[string]*HistogramData),
		ttl:        ttl,
		persistent: persistent,
	}
}

// Name 返回状态名称
func (s *MemoryHistogramState) Name() string {
	return s.name
}

// Type 返回状态类型
func (s *MemoryHistogramState) Type() store.StateType {
	return store.StateTypeHistogram
}

// Scope 返回状态作用域
func (s *MemoryHistogramState) Scope() store.StateScope {
	return store.StateScopeLocal
}

// Close 关闭状态
func (s *MemoryHistogramState) Close(ctx context.Context) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.data = make(map[string]*HistogramData)
	return nil
}

// Record 记录值
func (s *MemoryHistogramState) Record(ctx context.Context, key string, value float64) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	data, ok := s.data[key]
	if !ok {
		data = &HistogramData{
			Values: make([]float64, 0),
			Count:  0,
			Sum:    0,
			Min:    value,
			Max:    value,
		}
		s.data[key] = data
	}
	data.Values = append(data.Values, value)
	data.Count++
	data.Sum += value
	if value < data.Min {
		data.Min = value
	}
	if value > data.Max {
		data.Max = value
	}
	return nil
}

// Reset 重置直方图
func (s *MemoryHistogramState) Reset(ctx context.Context, key string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.data, key)
	return nil
}

// Count 获取计数
func (s *MemoryHistogramState) Count(ctx context.Context, key string) (int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, nil
	}
	return data.Count, nil
}

// Sum 获取总和
func (s *MemoryHistogramState) Sum(ctx context.Context, key string) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, nil
	}
	return data.Sum, nil
}

// Min 获取最小值
func (s *MemoryHistogramState) Min(ctx context.Context, key string) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, errors.New("histogram not found")
	}
	if data.Count == 0 {
		return 0, errors.New("histogram is empty")
	}
	return data.Min, nil
}

// Max 获取最大值
func (s *MemoryHistogramState) Max(ctx context.Context, key string) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, errors.New("histogram not found")
	}
	if data.Count == 0 {
		return 0, errors.New("histogram is empty")
	}
	return data.Max, nil
}

// Mean 获取平均值
func (s *MemoryHistogramState) Mean(ctx context.Context, key string) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, errors.New("histogram not found")
	}
	if data.Count == 0 {
		return 0, errors.New("histogram is empty")
	}
	return data.Sum / float64(data.Count), nil
}

// Percentile 获取百分位数
func (s *MemoryHistogramState) Percentile(ctx context.Context, key string, p float64) (float64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	data, ok := s.data[key]
	if !ok {
		return 0, errors.New("histogram not found")
	}
	if data.Count == 0 {
		return 0, errors.New("histogram is empty")
	}
	if p < 0 || p > 1 {
		return 0, errors.New("percentile must be between 0 and 1")
	}
	// 复制并排序值
	values := make([]float64, len(data.Values))
	copy(values, data.Values)
	sort.Float64s(values)
	// 计算索引
	index := int(float64(len(values)-1) * p)
	return values[index], nil
}

// Keys 获取所有键
func (s *MemoryHistogramState) Keys(ctx context.Context) ([]string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	keys := make([]string, 0, len(s.data))
	for key := range s.data {
		keys = append(keys, key)
	}
	return keys, nil
}

// Create 创建状态存储
func (f *MemoryStateStoreFactory) Create(ctx context.Context, config map[string]interface{}) (store.StateStore, error) {
	stateStore := NewMemoryStateStore()
	err := stateStore.Init(ctx, config)
	if err != nil {
		return nil, err
	}
	return stateStore, nil
}

// NewMemoryStateStoreFactory 创建一个新的内存状态存储工厂
func NewMemoryStateStoreFactory() *MemoryStateStoreFactory {
	return &MemoryStateStoreFactory{}
}
